package br.com.rglariguet.pioneer.util;

import java.beans.PropertyEditorSupport;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import br.com.rglariguet.pioneer.enums.EnumVisualizavel;

public class EnumHelper extends PropertyEditorSupport {

	private MessageSource messageSource;
	private Class clazz;

	public EnumHelper(Class clazz) {
		this(null, clazz);
	}

	public EnumHelper(MessageSource messageSource, Class clazz) {
		this.messageSource = messageSource;
		this.clazz = clazz;
	}

	public String getDescricao() {
		if (getValue() == null) {
			return "";
		}
		if (!(getValue() instanceof EnumVisualizavel)) {
			return ((Enum) getValue()).name();
		}
		EnumVisualizavel value = (EnumVisualizavel) getValue();
		String code = value.getDescricao();
		if (code == null || messageSource == null) {
			return ((Enum) getValue()).name();
		}
		String message = messageSource.getMessage(code, new String[] {},
				LocaleContextHolder.getLocale());
		return message;
	}

	public void setAsText(String text) throws IllegalArgumentException {
		setValue(Enum.valueOf(clazz, text));
	}
}